#include "uart.c"
#include "timer.c"
#include <regx52.h>

/**
 * 等待用户出拳，点击按钮代表出拳石头剪刀布。系统随机出拳。
 * 决出胜负，胜利方灯亮。点击按钮重新开始游戏。
 */

sbit BTN_START = P1^0; //开始/重置按键
sbit BTN_ROCK = P1^1; //石头
sbit BTN_PAPER = P1^2; //布
sbit BTN_SCISSOR = P1^3; //剪刀

sbit LED_USER_WIN = P2^7; //用户胜利指示灯
sbit LED_COMP_WIN = P2^0; //电脑胜利指示灯
//平局的话就不显示任何一方获胜（都不亮灯）

//用户方结果
sbit USER_ROCK = P2 ^ 6;
sbit USER_SCISSOR = P2 ^ 5;
sbit USER_PAPER = P2 ^ 4;

//系统方结果
sbit SYSTEM_ROCK = P2 ^ 1;
sbit SYSTEM_SCISSOR = P2 ^ 2;
sbit SYSTEM_PAPER = P2 ^ 3;

unsigned int result;
unsigned int player_choice;
unsigned int system_choice;

//定义石头剪刀布的值
#define ROCK 0
#define PAPER 1
#define SCISSORS 2

//开始按钮按下(初始化)
void start() {
    while (BTN_START == 1); 
    delay_ms(20); 
    P2 = 0xff;//所有灯全灭   
    while (BTN_START == 0);
    delay_ms(20);    
}

//获取用户选择（返回0-2表示石头-剪刀-布）
int get_user_choice() {
    while (1) {
        if (BTN_ROCK == 0) {
            delay_ms(20);
            if (BTN_ROCK == 0) {
                while (BTN_ROCK == 0); 
                USER_ROCK = 0;
                return ROCK;
            }
        }
        if (BTN_PAPER == 0) {
            delay_ms(20);
            if (BTN_PAPER == 0) {
                while (BTN_PAPER == 0);
                USER_PAPER = 0;
                return PAPER;
            }
        }
        if (BTN_SCISSOR == 0) {
            delay_ms(20);
            if (BTN_SCISSOR == 0) {
                while (BTN_SCISSOR == 0);
                USER_SCISSOR = 0;
                return SCISSORS;
            }
        }
    }
}

//判断胜负
int outcome(int player, int system) {
    if (player == system) return 0;  // 平局
    if ((player == ROCK && system == SCISSORS) ||
        (player == PAPER && system == ROCK) ||
        (player == SCISSORS && system == PAPER)) {
        return 1;  // 玩家胜
    }
    return -1;  // 电脑胜
}

// 显示结果
void show_result(int result) {

    LED_USER_WIN = 1;
    LED_COMP_WIN = 1;
    
    //根据结果点亮对应灯
    if (result == 1) {
        LED_USER_WIN = 0;//玩家胜利
    } else if (result == -1) {
        LED_COMP_WIN = 0;//电脑胜利
    } else {
        LED_USER_WIN = 1;
        LED_COMP_WIN = 1;//平局
    }
}

void main() {
    
    //初始化
    uart_init();
    timer0_init();
    
    // 初始化LED为熄灭状态
    LED_USER_WIN = 1;
    LED_COMP_WIN = 1;

    while (1) {
     
        //开始按钮
        start();
        
        //获取用户选择
        player_choice = get_user_choice();
        
        //系统随机出拳
        system_choice = timer_rand() % 3;
        switch(system_choice)
        {
            case 0: SYSTEM_ROCK = 0;break;
            case 1: SYSTEM_PAPER = 0;break;
            case 2: SYSTEM_SCISSOR = 0;break;

        }
        
        //判断胜负
        result = outcome(player_choice, system_choice);
        
        //显示结果3秒
        show_result(result);

    }
}